package br.ufrgs.dbproject.pathcache;

import java.util.LinkedList;
import java.util.List;

import br.ufrgs.dbproject.exceptions.DataNotFoundException;

/**
 * Cache used to store {@link Path} elements
 * avoiding waste of processing by recalculating paths that were already processed.
 * 
 * @author diego
 */
public class Cache {

	private final List<CacheEntry> cacheEntries;

	/**
	 * Creates a new empty cache.
	 */
	public Cache() {
		this.cacheEntries = new LinkedList<CacheEntry>();
	}

	/**
	 * Creates a new {@link Cache} with a custom cache entries.
	 * 
	 * @param cacheEntries the entries of the cache.
	 */
	public Cache(List<CacheEntry> cacheEntries) {
		this.cacheEntries = cacheEntries;
	}

	/**
	 * Puts a new entry into the cache.
	 * 
	 * @param key the Unique identifier of the path.
	 * @param path the new {@link Path}.
	 * 
	 * @return the cache entry for the cached {@link Path}.
	 */
	public CacheEntry put(Integer key, Path path) {
		
		CacheEntry entry = new CacheEntry(key, path);
		cacheEntries.add(entry);
		
		return entry;
	}

	/**
	 * Fetches a cache entry by it's {@link Path} value.
	 * 
	 * @param path the Path used as fetch parameter. 
	 * 
	 * @return the cache entry if existent
	 * 
	 * @throws DataNotFoundException Thrown if the Path is not in the cache yet.
	 */
	public CacheEntry fetchEntry(Path path) throws DataNotFoundException {
		
		for (int i = cacheEntries.size() - 1; i >= 0; i--) {
			
			CacheEntry entry = cacheEntries.get(i);
			if (entry.getPath().equals(path)) {
				return entry.markAsFetched();
			}
		}
		
		throw new DataNotFoundException("path " + path + " not found.");
	}
}
